package edu.mcw.rgd.clinminer.domain.misc;

import java.util.Date;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.PersistenceContext;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;

import edu.mcw.rgd.clinminer.domain.Participant;

@RooJavaBean
@RooToString
@RooJpaActiveRecord
@Table(name = "USER_PROFILE")
@NamedQuery(name = "UserProfile.findByName", query = "SELECT c FROM UserProfile c WHERE c.username = :name")
public class UserProfile {
	@Id
	@GeneratedValue(generator = "User_Profile_IDs_Seq")
	@SequenceGenerator(name = "User_Profile_IDs_Seq", sequenceName = "User_Profile_IDs_Seq", allocationSize = 1)
	@Column(name = "user_profile_id")
	private Long id;

	@Column(name = "username", unique = true, updatable = false)
	private String username;

	@JoinColumn(name = "default_participant")
	@ManyToOne
	private Participant defaultParticipant;

	@Column(name = "default_document_source")
	private String defaultDocumentSource;

	@DateTimeFormat(style = "S-")
	@Temporal(TemporalType.TIMESTAMP)
	@Column(name = "default_document_date")
	private Date defaultDocumentDate;

	public static UserProfile findByName(String name) {
		UserProfile p;
		// search for profile
		List<UserProfile> profiles = entityManager()
				.createNamedQuery("UserProfile.findByName", UserProfile.class)
				.setParameter("name", name).getResultList();
		if (!profiles.isEmpty()) {
			p = profiles.get(0);
		} else { // create new profile
			p = new UserProfile();
			p.setUsername(name);
			p.persist();
		}
		return p;
	}

	@PersistenceContext(unitName="persistenceUnit")
    transient EntityManager entityManager;
}
